package com.xtayfjpk.security.jsse;

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;

import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManagerFactory;

/**
 * 	-Djavax.net.ssl.keyStore=clientKeys
	-Djavax.net.ssl.keyStorePassword=password
	-Djavax.net.ssl.trustStore=clientTrust
	-Djavax.net.ssl.trustStorePassword=password
 * @author zj
 *
 */
public class SimpleSSLServer {
	
	public static void main(String[] args) throws Exception {
		SSLContext context = SSLContext.getInstance("SSL");
		String keyStorePassword = "password";
		KeyStore serverKeys = getKeyStore("serverKeys", "jks", keyStorePassword);
		System.out.println(KeyManagerFactory.getDefaultAlgorithm());
		KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
		String privateKeyPassword = "password";
		keyManagerFactory.init(serverKeys, privateKeyPassword.toCharArray());
		
		TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
		String trustStorePassword = "password";
		KeyStore serverTrustKeys = getKeyStore("serverTrust", "jks", trustStorePassword);
		trustManagerFactory.init(serverTrustKeys);
		context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
		
		
		
		
		SSLServerSocketFactory ssf = (SSLServerSocketFactory) context.getServerSocketFactory();
		//如果使用getDefault方式，则需要设置-Djavax.net.ssl.keyStore=clientKeys等系统属性
		//SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
		SSLServerSocket serverSocket = (SSLServerSocket) ssf.createServerSocket(9999);
		serverSocket.setNeedClientAuth(true);
		
		int id = 1;
		while(true) {
			try {
				String ident = String.valueOf(id++);
				SSLSocket socket = (SSLSocket) serverSocket.accept();
				HandshakeCompletedListener listener = new SimpleHandleShakeListener(ident);
				socket.addHandshakeCompletedListener(listener);
				InputStream in = socket.getInputStream();
				
				byte[] buf = new byte[1024];
				int len = in.read(buf);
				System.out.println(new String(buf, 0, len));
				in.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
			
	}
	
	public static KeyStore getKeyStore(String keyStorePath, String type, String keyStorePassword) throws Exception {
		KeyStore keyStore = KeyStore.getInstance(type);
		FileInputStream in = new FileInputStream(keyStorePath);
		keyStore.load(in, keyStorePassword.toCharArray());
		in.close();
		return keyStore;
	}
}
